/**
 * 用户个人主页
 */
$(function () {
    var user_id = $("#user").data("id"),
            active_tab = $("#user").data("tab"),
            loginname = $("#user").data("loginname"),
            // 用户信息显示表单
            email = $("#email"),
            male = $("#male"),
            dateOfBirth = $("#dateOfBirth"),
            maritalStatus = $("#maritalStatus"),
            education = $("#education"),
            school = $("#school"),
            address = $("#address"),
            industry = $("#industry"),
            companySize = $("#companySize"),
            position = $("#position"),
            salary = $("#salary"),
            // 用户编辑表单
            email_input = $("input[name=email]"),
            dateOfBirth_input = $("input[name=dateOfBirth]"),
            maritalStatus_select = $("select[name=maritalStatus]"),
            education_select = $("select[name=education]"),
            school_input = $("input[name=school]"),
            address_input = $("input[name=address]"),
            industry_select = $("select[name=industry]"),
            companySize_select = $("select[name=companySize]"),
            position_input = $("input[name=position]"),
            salary_select = $("select[name=salary]"),
            // buttons
            saveUserInfo = $("#saveUserInfo"),
            cancelInfoEdit = $("#cancelInfoEdit"),
            showEditPanel = $("#showEditPanel"),
            displayInfo = $("#displayInfo"),
            editInfo = $("#editInfo"),
            addImageBtn = $("#addImageBtn"),
            upload_btn_default = '<i class="fa fa-check mr10"></i>保存图片',
            upload_btn_process = '<i class="fa fa-spin fa-spinner mr10"></i>上传中...',
            imageContainer = $("#image-container"),
            // 资金记录
            fundType = $("select[name=fundType]"),
            fundOperation = $("select[name=fundOperation]"),
            fundStatus = $("select[name=fundStatus]");

    /**
     * 设置当前显示的tab页
     */
    if (active_tab !== '') {
        $("#li-" + active_tab).addClass("active");
        $("#tab-" + active_tab).addClass("active");
    } else {
        $("#li-info").addClass("active");
        $("#tab-info").addClass("active");
    }

    /**
     * 刷新页面并跳转到相应tab
     */
    var url = location.href.split('?tab=')[0];
    var getUrl = {
        info: url + "?tab=info",
        images: url + "?tab=images",
        fund: url + "?tab=fund",
        loans: url + "?tab=loans",
        invests: url + "?tab=invests"
    };
    var refresh = function (tab) {
        location.href = getUrl[tab];
    };

    /**
     * 读取资金账户
     */
    var initUserFund = function (fund) {
        if (fund !== null) {
            $("#available-amount").text($.number(fund.available, 2));
            $("#frozen-amount").text($.number(fund.frozen, 2));
            $("#receivable-amount").text($.number(fund.payable, 2));
            $("#payable-amount").text($.number(fund.receivable, 2));
            $("#total-deposit").text($.number(fund.totalDeposit, 2));
            $("#total-withdraw").text($.number(fund.totalWithdraw, 2));
        } else {
            alert("读取用户资金账户失败");
        }
    };

    var zpad = function (n, l) {
        return rep(l - n.toString().length, '0') + n.toString();
    };

    /**
     * 载入用户详细信息 
     */
    var initUserInfo = function (data) {
        $("#userSource").text(data.info.source || '-');
        $("#userCampaign").text(data.info.campaign || '-');
        $("#userTerm").text(data.info.term || '-');
        $("#total-bonus").html($.number(data.info.bonus, 2));

        $("input[name=male][value=" + data.info.male + "]").prop("checked", true);

        /**
         * 初始化用户信息显示
         */
        var blank_text = '尚未填写'; // birthDate = data.info.dateOfBirth.year + '/' + ("0" + data.info.dateOfBirth.monthValue).slice(-2) + '/' + data.info.dateOfBirth.dayOfMonth;

        email.text(data.info.email ? data.info.email : blank_text);
        male.text(data.info.male ? '男' : '女');
        dateOfBirth.text(data.dateOfBirth ? data.dateOfBirth : blank_text);
        maritalStatus.text(data.maritalStatus ? data.maritalStatus : blank_text);
        education.text(data.education ? data.education : blank_text);
        school.text(data.info.school ? data.info.school : blank_text);
        address.text(data.info.address ? data.info.address : blank_text);
        industry.text(data.industry ? data.industry : blank_text);
        companySize.text(data.companySize ? data.companySize : blank_text);
        position.text(data.info.position ? data.info.position : blank_text);
        salary.text(data.salary ? data.salary : blank_text);
        /**
         * 初始化用户信息编辑
         */
        email_input.val(data.info.email);
        male.val(data.info.male ? true : false);
        dateOfBirth_input.val(data.dateOfBirth);
        //if (data.info.dateOfBirth) {
        //    dateOfBirth_input.datepicker('setDate', new Date(data.info.dateOfBirth));
        //}
        maritalStatus_select.val(data.info.maritalStatus);
        education_select.val(data.info.education);
        school_input.val(data.info.school);
        address_input.val(data.info.address);
        industry_select.val(data.info.industry);
        companySize_select.val(data.info.companySize);
        position_input.val(data.info.position);
        salary_select.val(data.info.salary);
    };
    /**
     * 初始化资金记录列表
     */
    var initFundRecordTable = function () {
        // 初始化资金类型下拉列表
        for (var type in sysFundType) {
            fundType.append($("<option></option>").attr("value", type).text(sysFundType[type]));
        }
        // 初始化操作类型下拉列表
        for (var type in sysFundOperation) {
            fundOperation.append($("<option></option>").attr("value", type).text(sysFundOperation[type]));
        }
        // 初始化资金状态下拉列表
        for (var type in sysFundStatus) {
            fundStatus.append($("<option></option>").attr("value", type).text(sysFundStatus[type]));
        }
        // 初始化列表
        var table = $('#fundRecordList').DataTable({
            "processing": true,
            "serverSide": true,
            "ajax": {
                "url": "fund/getUserFundRecord",
                "data": function (d) {
                    d.userId = user_id;
                    d.fundType = fundType.val();
                    d.fundOperation = fundOperation.val();
                    d.fundStatus = fundStatus.val();
                },
                "type": "POST"
            },
            "aoColumnDefs": [{
                    "targets": 0, //订单号
                    "mRender": function (data, type, row) {
                        return row.record.orderId;
                    }
                }, {
                    "targets": 1, //流水号
                    "visible": false,
                    "mRender": function (data, type, row) {
                        return row.record.transId;
                    }
                }, {
                    "targets": 2, //金额
                    "mRender": function (data, type, row) {
                        return $.number(row.record.amount, 2);
                    }
                }, {
                    "targets": 4, //相关标的
                    "mRender": function (data, type, row) {
                        return row.loan === null
                                ? '-'
                                : '<a href="loan/detail/' + row.loan.id + '" target="_blank">' + row.loan.title + '</a>';
                    }
                }, {
                    "targets": 3, //资金类型
                    "mRender": function (data, type, row) {
                        return sysFundType[row.record.type];
                    }
                }, {
                    "targets": 5, //操作类型
                    "mRender": function (data, type, row) {
                        return sysFundOperation[row.record.operation];
                    }
                }, {
                    "targets": 6, //资金状态
                    "mRender": function (data, type, row) {
                        return sysFundStatus[row.record.status];
                    }
                }, {
                    "targets": 7, //操作时间
                    "searchable": false,
                    "mRender": function (data, type, row) {
                        return $.format.date(new Date(row.record.recordTime), "yyyy/MM/dd HH:mm");
                    }
                }, {
                    "targets": 8, //备注
                    "searchable": false,
                    "mRender": function (data, type, row) {
                        return row.record.description;
                    }
                }],
            "order": [7, 'desc'],
            "oLanguage": chinese,
            "language": {
                "decimal": ",",
                "thousands": ",",
            },
            "iDisplayLength": 20,
            "aLengthMenu": [
                [5, 10, 20, 50, 100, -1],
                [5, 10, 20, 50, 100, "全部"]
            ],
            "sDom": 't<"dt-panelfooter clearfix"lp>',
            "initComplete": function (settings, json) {
                $("#fundCount").text(json.recordsTotal);
            }
        });

        $('#searchFundRecord').on('click', function () {
            table.ajax.reload();
        });
    };

    /**
     * 初始化借款列表
     */
    var initLoanTable = function () {
        var table = $('#loanTable').DataTable({
//    "processing": true,
//    "serverSide": true,
            "ajax": "loan/getDataByUser/" + user_id,
            "columns": [
                {"data": "loan"},
                {"data": "loan"},
                {"data": "loan"},
                {"data": "loan"},
                {"data": "loan"},
                {"data": "loan"},
                {"data": "loan"}
            ],
            "aoColumnDefs": [{
                    "targets": 0, //标题 
                    "mRender": function (data, type, row) {
                        return data === ''
                                ? '未填写'
                                : '<a href="loan/detail/' + data.id + '">' + data.title + '</a>';
                    }
                }, {
                    "targets": 1, //金额
                    "mRender": function (data, type, row) {
                        return $.number(data.amount);
                    }
                }, {
                    "targets": 2, //年利率
                    "mRender": function (data, type, row) {
                        return $.number(parseFloat(data.rate / 100), 1) + '%';
                    }
                }, {
                    "targets": 3, //借款周期
                    "mRender": function (data, type, row) {
                        return sys.printDuration(data.duration);
                    }
                }, {
                    "targets": 4, //还款方式
                    "mRender": function (data, type, row) {
                        return sys.getRepayMethod(data.repayMethod);
                    }
                }, {
                    "targets": 5, //状态
                    "searchable": false,
                    "mRender": function (data, type, row) {
                        return sys.getLoanStatus(data.status);
                    }
                }, {
                    "targets": 6, //申请时间
                    "searchable": false,
                    "mRender": function (data, type, row) {
                        return data !== null
                                ? $.format.date(new Date(data.submitTime), "yy/MM/dd HH:mm")
                                : '';
                    }
                }],
            "order": [6, "desc"],
            "oLanguage": chinese,
            "language": {
                "decimal": ",",
                "thousands": ","
            },
            "iDisplayLength": 20,
            "aLengthMenu": [
                [5, 10, 20, 50, -1],
                [5, 10, 20, 50, "全部"]
            ],
            "sDom": 't<"dt-panelfooter clearfix"lp>',
            "initComplete": function (settings, json) {
                $("#loanCount").text(json.recordsTotal);
            }
        });
    };

    /**
     * 初始化投标记录
     */
    var initInvestTable = function () {
        var table = $('#investTable').DataTable({
//    "processing": true,
//    "serverSide": true,
            "ajax": "user/getInvestData/" + user_id,
            "columns": [
                {"data": "loanTitle"},
                {"data": "amount"},
                {"data": "status"},
                {"data": "investTime"}
            ],
            "aoColumnDefs": [{
                    "targets": 0, //标的名称 
                    "mRender": function (data, type, row) {
                        return '<a href="loan/detail/' + row.loanId + '" target="_blank">' + data + '</a>';
                    }
                }, {
                    "targets": 1, //金额
                    "mRender": function (data, type, row) {
                        return $.number(data);
                    }
                }, {
                    "targets": 3, //投标时间
                    "searchable": false,
                    "mRender": function (data, type, row) {
                        return $.format.date(new Date(data), "yyyy/MM/dd HH:mm");
                    }
                }, {
                    "targets": 2, //状态
                    "searchable": false,
                    "mRender": function (data, type, row) {
                        return sysInvestStatus[data];
                    }
                }],
            "order": [3, "desc"],
            "oLanguage": chinese,
            "language": {
                "decimal": ",",
                "thousands": ","
            },
            "iDisplayLength": 20,
            "aLengthMenu": [
                [5, 10, 20, 50, -1],
                [5, 10, 20, 50, "全部"]
            ],
            "sDom": 't<"dt-panelfooter clearfix"lp>',
            "initComplete": function (settings, json) {
                $("#investCount").text(json.recordsTotal);
            }
        });
    };

    /**
     * 初始化积分记录
     */
    var initPointsTable = function () {
        // 初始化列表
        var table = $('#pointsTable').DataTable({
            "processing": true,
            "serverSide": true,
            "ajax": {
                "url": "pointsystem/getPointsList",
                "data": function (d) {
                    d.userId = user_id;
                    var dateRange = dateRangePicker.val().split(" - ");
                    d.startTime = new Date(dateRange[0]);
                    var endTime = moment(dateRange[1], "YYYY-MM-DD").endOf('day');
                    d.endTime = new Date(endTime);
                    d.pointsOperation = $('select[name="pointsOperation"]').val();
                },
                "type": "POST"
            },
            sortable: false,
            "columnDefs": [{
                    "targets": 0, //时间
                    "sClass": 'title',
                    "mRender": function (data, type, row) {
                        return $.format.date(new Date(row.recordTime), 'yyyy-MM-dd HH:mm:ss');
                    }
                }, {
                    "targets": 1, // 类型
                    "mRender": function (data, type, row) {
                        return sysPointsOperation[row.pointsOperation];
                    }
                }, {
                    "targets": 2, // 积分
                    "mRender": function (data, type, row) {
                        return row.points;
                    }
                },
                {
                    "targets": 3, // 积分类型
                    "mRender": function (data, type, row) {
                        return sysPointType[row.pointTypeId];
                    }
                },
                {
                    "targets": 4, // 余额
                    "mRender": function (data, type, row) {
                        return row.balance;
                    }
                },
                {
                    "targets": 5, // 冻结积分
                    "mRender": function (data, type, row) {
                        return row.freezing_amount;
                    }
                }
            ],
            "oLanguage": chinese,
            "language": {
                "decimal": ",",
                "thousands": ","
            },
            "iDisplayLength": 20,
            "aLengthMenu": [
                [5, 10, 20, 50, -1],
                [5, 10, 20, 50, "全部"]
            ],
            "sDom": 't<"dt-panelfooter clearfix"lp>',
            "initComplete": function (settings, json) {
                $("#pointsCount").text(json.recordsTotal);
            }
        });
        $('#searchPoints').on('click', function () {
            table.ajax.reload();
        });

        /**
         * 扣除積分显示
         * @returns 
         */
        $("#out_points").on('click', function () {
            $("#li-points").removeClass("active");
            $("#userId").val(user_id);
            $('#myModal').modal('show');
            $("#li-points").removeClass("active");
        });
        /**
         * 扣除积分
         * @returns 
         */
        $("#confirm_deduction").on('click', function () {
            var userId = user_id;
            var point = $("#deduction_points").val();
            var type = $("#operationtype").val();
            var remark = $("#remark_points").val();
            if(point <= 0){
                alert("积分必须大于0");
                return;
            }
            if(point == ''){
                alert("请填写积分");
                return;
            }
             if(isNaN(point)){
                 alert("扣除的积分必须为数字");
                 return;
             }
            $.ajax({
                url: "pointsystem/deduction",
                data: {userid: userId,point:point,type:type,remark:remark},
                type: 'POST',
                async: false,
                success: function (res) {
                    if(res.success){
                    alert(res.message);
                    $('#myModal').modal('hide');
                    location.reload();
                }else{
                    alert(res.message);
                }
                }
            }).fail(function () {
                alert('服务器错误');
            });
        });
    };

    /**
     *  初始化日历
     */
    var initDatePicker = function () {
        dateOfBirth_input.datepicker({
            prevText: '<i class="fa fa-chevron-left"></i>',
            nextText: '<i class="fa fa-chevron-right"></i>',
            showButtonPanel: false
        });
        // 设置默认日期
        dateOfBirth_input.datepicker('setDate', new Date());
    };

    /**
     * 初始化图片上传控件
     */
    var initUploader = function () {
        var doUploadBtn = $("#doUploadBtn"), document = null;
        /**
         * 弹出文件选择框
         */
        $('#upZone').click(function () {
            $('#fileInput').click();
        });
        $('#fileInput').on("change", function (e) {
            var files = e.target.files;
            if (!files.length || !window.FileReader) {
                return; // no file selected, or no FileReader support
            }
            document = files[0];
            $("#fileName").val(document.name);
            if (/^image/.test(document.type)) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    $("#imagePreview").html($('<img class="h-150"/>').attr('src', e.target.result));
                };
                reader.readAsDataURL(document);
            }
        });
        /**
         * 保存图片：触发上传
         */
        doUploadBtn.on("click", function () {
            if (document === null) {
                alert("尚未选择图片");
            } else {
                $('form[name=uploadForm]').trigger('submit');
            }
        });
        /**
         *  上传文件
         */
        $('form[name=uploadForm]').on('submit', function (event) {
            event.stopPropagation();
            event.preventDefault();

            var url = 'store/upload';
            var formData = new FormData();
            formData.append("file", document);
            formData.append("name", $("#fileName").val());
            formData.append("desc", $("#description").val());
            formData.append("realm", 'USER');
            formData.append("id", user_id);

            doUploadBtn.prop("disabled", true).html(upload_btn_process);
            $.ajax({
                url: url,
                data: formData,
                processData: false,
                contentType: false,
                type: 'POST',
                success: function (res) {
                    doUploadBtn.html(upload_btn_default).prop("disabled", false);
                    if (res.success) {
                        alert("图片上传成功！");
                        refresh("images");
                    } else {
                        alert(res.message);
                    }
                }
            }).fail(function () {
                alert('图片上传失败：服务器错误');
            });
        });
    };

    /**
     * 初始化事件
     */
    var initEvents = function () {
        // 账号激活/冻结
        $("#changeStatus").on("click", function () {
            if (confirm('确定要更新用户状态？')) {
                $.get("user/changeStatus/" + user_id, function (res) {
                    if (res.success) {
                        alert(res.message);
                        refresh("info");
                    } else {
                        alert("用户状态更新失败");
                    }
                });
            }
        });
        /**
         * 用户重置密码
         */
        $("#resetPasswordBtn").on("click", function () {
            if (confirm("确定重置该用户登录密码？")) {
                $.get("user/resetPassword/" + user_id, function (res) {
                    if (res.success) {
                        alert("用户密码已重置！新的随机密码已通过短信通知用户");
                    } else {
                        alert("用户密码重置失败");
                    }
                }).fail(function () {
                    alert("网络通信错误");
                });
            }
        });
        /**
         * 更新用户信息
         */
        saveUserInfo.on("click", function () {
            var data = $("#editInfoForm").formToJson(), birthDate = dateOfBirth_input.val();
            data.userId = user_id;
            if (birthDate !== '' && !/\d{4}-\d{2}-\d{2}/.test(birthDate)) {
                alert("出生日期格式不正确");
                return;
            }

            //data.dateOfBirth = $.format.date(new Date(dateOfBirth_input.val()), "yyyy-MM-dd");
            $.post("user/updateUserInfo", data, function (res) {
                if (res.success) {
                    alert(res.message);
                    refresh("info");
                } else {
                    alert(res.message);
                }
            });
        });
        /**
         * 取消用户编辑
         */
        cancelInfoEdit.on("click", function () {
            editInfo.hide();
            saveUserInfo.hide();
            cancelInfoEdit.hide();
            showEditPanel.show();
            displayInfo.show();
        });
        /**
         * 显示用户资料编辑面板
         */
        showEditPanel.on("click", function () {
            displayInfo.hide();
            showEditPanel.hide();
            saveUserInfo.show();
            cancelInfoEdit.show();
            editInfo.show();
        });
        /**
         * 添加图片
         */
        addImageBtn.on("click", function () {
            $.magnificPopup.open({
                removalDelay: 500, //delay removal by X to allow out-animation,
                alignTop: true,
                items: {
                    src: "#uploadPanel"
                },
                // overflowY: 'hidden', // 
                callbacks: {
                    beforeOpen: function (e) {
                        this.st.mainClass = 'mfp-slideDown';
                    }
                },
                midClick: true // allow opening popup on middle mouse click. Always set it to true if you don't provide alternative source.
            });
        });
        /**
         * 设置图片前端可见性
         */
        imageContainer.on("click", ".visible-link", function (e) {
            e.stopPropagation();
            e.preventDefault();
            var id = $(this).data("id"), visible = $(this).data("visible"), $this = $(this), msg = visible ? "前端不可见？" : "前端可见？";
            if (confirm("确定设置图片为" + msg)) {
                $.post("store/setImageVisible", {
                    id: id,
                    visible: visible ? false : true
                }, function (res) {
                    if (res === true) {
                        alert("设置图片可见性成功");
                        refresh("images");
                    }
                });
            }
        });
        /**
         * 刪除图片
         */
        imageContainer.on("click", ".delete-link", function (e) {
            e.stopPropagation();
            e.preventDefault();
            if (confirm("确定要删除图片？")) {
                var id = $(this).data("id");
                $.get("store/deleteImageById/" + id, function (res) {
                    if (res === true) {
                        alert("图片删除成功");
                        refresh("images");
                    } else {
                        alert("图片删除失败");
                    }
                });
            }
        });
    };

    // 初始化图片预览弹出框
    var initPopUp = function () {
        $('.image img').magnificPopup({
            type: 'image',
            callbacks: {
                beforeOpen: function (e) {
                    // we add a class to body to indicate overlay is active
                    // We can use this to alter any elements such as form popups
                    // that need a higher z-index to properly display in overlays
                    $('body').addClass('mfp-bg-open');

                    // Set Magnific Animation
                    this.st.mainClass = 'mfp-zoomIn';

                    // Inform content container there is an animation
                    this.contentContainer.addClass('mfp-with-anim');
                },
                afterClose: function (e) {
                    $('body').removeClass('mfp-bg-open');
                },
                elementParse: function (item) {
                    // Function will fire for each target element
                    // "item.el" is a target DOM element (if present)
                    // "item.src" is a source that you may modify
                    item.src = item.el.data('url');
                }
            },
            removalDelay: 200 //delay removal by X to allow out-animation
        });
    };

    /**
     * 获取用户认证图片
     */
    var loadImages = function () {
        $.post("store/listImageByOwner", {
            ownerId: user_id,
            realm: 'USER'
        }, function (data) {
            if (data && data.totalSize > 0) {
                for (var i = 0; i < data.totalSize; i++) {
                    var img = data.result[i];
                    img.createTime = function () {
                        return $.format.date(new Date(this.recordTime), "yyyy/MM/dd");
                    };
                    img.vclass = function () {
                        return this.visible ? 'text-system' : '';
                    };
                    var rendered = sys.render("#imageTemplate", img);
                    imageContainer.prepend($(rendered));
                }
                initPopUp();
            } else {
                $("#loading").html("尚未添加认证图片");
            }
        });
    };

    var loadUserData = function () {
        $.get("user/getDataById/" + user_id, function (data) {
            if (data) {
                initPnrAccountStatus(data.account);
                initUserFund(data.fund);
                initUserInfo(data);
                // 获取汇付账号信息
                initPaymentData();

                $("#loanCount").html(data.loanCount);
                $("#loanAmount").html($.number(data.loanAmount, 2));
                $("#investCount").html(data.investCount);
                $("#investAmount").html($.number(data.investAmount, 2));

                if (data.referee) {
                    $("#referee").html(sys.render("#refereeTemplate", data.referee));
                } else {
                    $("#referee").html('未指定');
                }
            }
        });
    };

    var initPnrAccountStatus = function (account) {
        var pnrAccount = $("#pnrAccount");
        if (account !== null) {
            pnrAccount.html('<span class="label label-xs label-system">已开通</span>');
            $("#pnrAccount").data("hasaccount", true);
        } else {
            pnrAccount.html('<span class="label bg-light darker label-xs">尚未开通</span>');
            $("#pnrAccount").data("hasaccount", false);
        }
    };
    /**
     * 注册校对按钮事件
     */
    var initPaymentBtns = function () {
        // 注册校对用户汇付真实余额事件
        $("#btn-payment-balance-calibrate").on("click", function () {
            if (confirm("是否根据汇付用户余额校准平台用户余额？")) {
                $.get("tool/calibratePnrBalance/" + user_id, function (data) {
                    if (data.success) {
                        alert("根据汇付用户余额校准平台用户余额: " + data.message);
                    } else {
                        alert("根据汇付用户余额校准平台用户余额:" + data.message);
                    }
                    location.reload();
                });
            }
        });
        // 注册校对用户汇付账号事件
        $("#btn-payment-account-calibrate").on("click", function () {
            if (confirm("是否根据汇付用户账号校准平台用户账号？")) {
                $.get("tool/syncUserPnrAccount/" + user_id, function (data) {
                    if (data.success) {
                        alert("根据汇付用户账号校准平台用户账号：" + data.message);
                        $("#pnrAccount").data("hasaccount", true);
                    } else {
                        alert("根据汇付用户账号校准平台用户账号：" + data.message);
                    }
                    location.reload();
                });
            }
        });
        $("#btn-payment-bankcard-calibrate").on("click", function () {
            if (confirm("是否根据汇付用户绑卡信息校准平台用户绑卡信息？")) {
                $.get("tool/syncUserBankCardInfo/" + user_id, function (data) {
                    if (data.success) {
                        alert("根据汇付用户绑卡信息校准平台用户绑卡信息：" + data.message);
                    } else {
                        alert("根据汇付用户绑卡信息校准平台用户绑卡信息：" + data.message);
                    }
                    location.reload();
                });
            }
        });
    };
    /**
     * 获取用户托管账户数据
     */
    var loadPaymentData = function () {
        // 查询用户汇付真实余额
        $.get("pnr/queryUserBalance/" + user_id, function (data) {
            if (typeof (data) !== 'undefined') {
                if (data.respCode === '000') { // UserBalanceResult返回成功
                    $("#payment-actual-balance").text(data.accountBalance);
                    $("#payment-actual-available").text(data.availableBalance);
                    $("#payment-actual-freeze").text(data.freezeBalance);
                } else {
                    $("#payment-actual-balance").text("-");
                    $("#payment-actual-available").text("-");
                    $("#payment-actual-freeze").text("-");
                }
            }
        });
        // 已开通三方支付，但是身份证信息未显示，可能是用户使用两个手机号，同一身份证信息开通第三方支付，导致身份证号冲突，系统无法保存
        // 提示平台联系用户本人，确认将未开通三方支付的账号身份证信息清空并禁用此账号，将已开通三方支付的账号身份证信息补全
        if ($("#pnrAccount").data("hasaccount")
                && $("#idNumber").data("idnumber") === '') {
            $("#idNumberConflictTips").removeClass("hidden");
            $("#conflictAccountTips").removeClass("hidden");
        }
        // 查询用户汇付真实账号信息
        if ($("#idNumber").data("idnumber") !== '') {
            $.get("pnr/queryUserInfo/" + user_id, function (data) {
                if (data.respCode === '000') { // QueryUsrInfoResult返回成功
                    $("#payment-actual-id").text(data.certId);
                    $("#payment-actual-usrId").text(data.usrId);
                    $("#payment-actual-usrCustId").text(data.usrCustId);
                }
            });
        }
        // 初始化汇付绑卡信息
        initBankCardTable();
    };
    /**
     * 初始化托管账户绑卡信息
     */
    var initBankCardTable = function () {
        var table = $('#bankCardTable').DataTable({
//    "processing": true,
//    "serverSide": true,
            "ajax": "pnr/queryUserCardInfo/" + user_id,
            "aoColumnDefs": [{
                "targets": 0, //开户行
                "mRender": function (data, type, row) {
                    return row.bank;
                }
            }, {
                "targets": 1, //金额
                "mRender": function (data, type, row) {
                    return row.cardId;
                }
            }, {
                "targets": 2, //投标时间
                "searchable": false,
                "mRender": function (data, type, row) {
                    return row.usrName;
                }
            }, {
                "targets": 3, //状态
                "searchable": false,
                "mRender": function (data, type, row) {
                    return row.isDefault;
                }
            }, {
                "targets": 4, //状态
                "searchable": false,
                "mRender": function (data, type, row) {
                    var operations = $("#operationHTML").html().replace(/#userId/g, user_id).replace(/#cardId/g, row.cardId);
                    return operations;
                }
            }],
            "order": [1, "desc"],
            "oLanguage": chinese,
            "language": {
                "decimal": ",",
                "thousands": ","
            },
            "iDisplayLength": 20,
            "aLengthMenu": [
                [5, 10, 20, 50, -1],
                [5, 10, 20, 50, "全部"]
            ],
            "sDom": 't<"dt-panelfooter clearfix"lp>',
        });
    };
    /**
     * 初始化托管账户数据
     */
    var initPaymentData = function () {
        initPaymentBtns();
        if ($("#pnrAccount").data("hasaccount")) {
            loadPaymentData();
        }
    };

    var loadFriends = function () {
        var friendPanel = $("#friends");
        $.get("user/listByReferee/" + user_id, function (res) {
            if (res && res.totalSize > 0) {
                friendPanel.html("");
                for (var i = 0; i < res.totalSize; i++) {
                    var friend = res.result[i], span = $('<a href="user/index/' + friend.id + '" target="_blank" class="mr10"></a>').text(friend.loginName);
                    friendPanel.append($('<div class="mb5"></div>').append(span));
                }
            } else {
                $("#friends .load-info").html("尚未邀请好友");
            }
        });
    };

    var status = $("#content").data("status"),
            dateRangePicker = $('#daterangepicker');

    $(".repayment_" + status).addClass("active");
    var dateRangePicker = $('#daterangepicker');
    var initDateRangePicker = function () {
        var rangePast = {
            '今天': [moment(), moment()],
            '昨天': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
            '最近7天': [moment().subtract(6, 'days'), moment()],
            '最近30天': [moment().subtract(29, 'days'), moment()],
            '本月': [moment().startOf('month'), moment().endOf('month')],
            '上个月': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
        };
        var rangeFuture = {
            '今天': [moment(), moment()],
            '未来7天': [moment(), moment().add(6, 'days')],
            '未来30天': [moment(), moment().add(29, 'days')],
            '未来60天': [moment(), moment().add(59, 'days')],
            '本月': [moment().startOf('month'), moment().endOf('month')],
            '下个月': [moment().add(1, 'month').startOf('month'), moment().add(1, 'month').endOf('month')]
        };

        dateRangePicker.daterangepicker({
            ranges: rangePast,
            startDate: moment().subtract(29, 'days'),
            endDate: moment(),
            applyClass: "btn-primary btn-block",
            cancelClass: "btn-block",
            format: "YYYY-MM-DD",
            locale: {
                applyLabel: '确定',
                clearLabel: "取消",
                fromLabel: '开始时间',
                toLabel: '结束时间',
                weekLabel: '周',
                customRangeLabel: '选择范围',
                daysOfWeek: "日_一_二_三_四_五_六".split("_"),
                monthNames: "一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"),
                firstDay: 0
            },
            opens: "left"
        });

        var formatDate = function (date) {
            return $.format.date(new Date(date), "yyyy/MM/dd");
        };
        // 根据状态设定初始日期
        var defaultDate = formatDate(moment().subtract(29, 'days')) + ' - ' + formatDate(moment());
        dateRangePicker.val(defaultDate);
        $(".daterangepicker .ranges ul li:last").hide();
        $(".daterangepicker .ranges .daterangepicker_start_input").remove();
        $(".daterangepicker .ranges .daterangepicker_end_input").remove();
        $(".daterangepicker .ranges .cancelBtn").remove();
    };

    /**
     * 初始化我的推荐
     */
    var initRecommendTable = function () {
        var table = $('#recommendTable').DataTable({
            "ajax": "user/getRecommendData/" + loginname,
            "columns": [
                {"data": "userLoginName"},
                {"data": "userName"},
                {"data": "amount"},
                {"data": "investTime"},
                {"data": "status"},
                {"data": "points"}
            ],
            "aoColumnDefs": [{
                    "targets": 0, //投资人
                    "mRender": function (data, type, row) {
                        return '<a href="user/index/' + row.userId + '" target="_blank">' + data + '</a>';
                    }
                }, {
                    "targets": 1, //姓名
                    "mRender": function (data, type, row) {
                        return data;
                    }
                }, {
                    "targets": 2, //金额
                    "searchable": false,
                    "mRender": function (data, type, row) {
                        return $.number(data);
                        
                    }
                }, {
                    "targets": 3, //投资时间
                    "searchable": false,
                    "mRender": function (data, type, row) {
                        return $.format.date(new Date(data), "yyyy/MM/dd HH:mm");
                    }
                }, {
                    "targets": 4, //状态
                    "searchable": false,
                    "mRender": function (data, type, row) {
                        return sysInvestStatus[data];
                    }
                }, {
                    "targets": 5, //积分
                    "searchable": false,
                    "mRender": function (data, type, row) {
                        return data;
                    }
                }],
            "order": [3, "desc"],
            "oLanguage": chinese,
            "language": {
                "decimal": ",",
                "thousands": ","
            },
            "iDisplayLength": 20,
            "aLengthMenu": [
                [5, 10, 20, 50, -1],
                [5, 10, 20, 50, "全部"]
            ],
            "sDom": 't<"dt-panelfooter clearfix"lp>',
            "initComplete": function (settings, json) {
                $("#recommendCount").text(json.recordsTotal);
            }
        });
    };

    var initPage = function () {
        loadUserData();
        //queryUserBalance();
        initDateRangePicker();
        initEvents();
        //initUserInfo();
        //initUserFund();
        loadImages();
        initUploader();
        //initDatePicker();
        initFundRecordTable();
        initLoanTable();
        initInvestTable();
        loadFriends();
        initPointsTable();
        initRecommendTable();
    };
    // 初始化页面
    initPage();

    $.get("user/getAddressById", {"userId": user_id}, function (res) {
        if (res != null) {
            $("#user_address").html(res.address);
            $("#tel_number").html(res.tel_number);
            $("#consignee").html(res.username);
        }
    }).fail(function () {
        alert("网络通信错误");
    });
    
});

/**
 * 解绑银行卡
 * @param {type} userId
 * @param {type} cardId
 * @returns {undefined}
 */
function deleteCard(userId, cardId) {
    if (confirm('确定要解绑此银行卡？')) {
        $.post("user/deleteBankCard",{userId: userId, cardId: cardId}, function (res) {
            if (res.success) {
                alert("解绑银行卡成功");
                location.reload();
            } else {
                alert("解绑银行卡失败");
            }
        });
    }
}